package com.halflife.comeElectricity.orderMng.cancel;

import com.halflife.comeElectricity.member.merchant.Merchant;
import com.halflife.comeElectricity.orderMng.order.*;
import com.halflife.comeElectricity.orderMng.order.vo.OrderVO;
import com.halflife.shiro.utils.ShiroUtil;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.shape.Rectangle;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * Created by liuj on 2018/2/12.
 */
@RestController
@RequestMapping("mc_cancelOrder")
public class CancelOrderController {

    private Logger log = LoggerFactory.getLogger(CancelOrderController.class);
    @Resource
    private CancelOrderRepository cancelOrderRepository;
    @Resource
    private CancelOrderExtRepository cancelOrderExtRepository;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderExtRepository orderExtRepository;

    /**
     * 生成取消訂單 並刪除訂單 add by liuj3
     * @param orderId
     */

    public void add(Integer orderId){
        try {
            BeanUtilsBean beanUtilsBean = new BeanUtilsBean();
            beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.BigDecimalConverter(null), BigDecimal.class);
            //查詢訂單以及訂單詳情
            if(orderId!=null) {
                //获取订单
                Order order = orderRepository.selectByPrimaryKey(orderId);
                //更新訂單狀態 已取消-9 退款中
                if(order.getStatus()==OrderEnum.WAITTOGET.m_orderStatus.byteValue())
                    order.setStatus(OrderEnum.PAYREFND.m_orderStatus.byteValue());
                else
                    order.setStatus(OrderEnum.CANCEL.m_orderStatus.byteValue());
                //复制Order对象
                CancelOrder cancelOrder = new CancelOrder();
                beanUtilsBean.copyProperties(cancelOrder, order);
                cancelOrder.setId(null);
                cancelOrder.setCancelDate(Calendar.getInstance().getTimeInMillis());
                //创建取消订单
                Integer cancelOrderId = cancelOrderRepository.insert(cancelOrder);
                //获取订单详情
                OrderExt orderExt = orderExtRepository.selectByPrimaryKey(orderId);
                //复制订单详情
                CancelOrderExt orderExt_c = new CancelOrderExt();
                orderExt_c.setEndTime(Calendar.getInstance().getTimeInMillis());
                beanUtilsBean.copyProperties(orderExt_c, orderExt);
                //指定订单详情id对应CancelOrder
                orderExt_c.setId(cancelOrder.getId());
                //创建取消订单详情
                cancelOrderExtRepository.insert(orderExt_c);
                //删除订单以及订单详情
                orderRepository.deleteByPrimaryKey(orderId);
                orderExtRepository.deleteByPrimaryKey(orderId);
            }
        } catch (Exception e) {
            log.error("================订单取消错误===================");
            log.error(e.getMessage(), e);
        }
    }

    //获取已取消订单管理列表 edit by liuj3
    @GetMapping("/list")
    @ResponseStatus(HttpStatus.CREATED)
    // public ResponseEntity<List<CancelOrder>> list(@RequestParam(value="id",defaultValue = "null") Integer id,
    public ResponseEntity<CancelOrderCallBack> list(@RequestParam(value="longitude", required = false) Integer longitude,
                                                    @RequestParam(value="latitude", required = false) Integer latitude,
                                                    @RequestParam(value="currentPage",defaultValue = "1") Integer currentPage,
                                                    @RequestParam(value="pageSize",defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest request){
        //oper 分页类型 0-进行中订单 1-已完成订单 -1-已取消订单
        Merchant merchant  =  ShiroUtil.getMerchant(request);
        if (longitude != null && latitude != null) {
            int radius =1;//千米
            SpatialContext geo = SpatialContext.GEO;
            Rectangle rectangle = geo.getDistCalc().calcBoxByDistFromPt(
                    geo.makePoint(longitude, latitude), radius * DistanceUtils.KM_TO_DEG, geo, null);
            System.out.println(rectangle.getMinX() + "-" + rectangle.getMaxX());// 经度范围
            System.out.println(rectangle.getMinY() + "-" + rectangle.getMaxY());// 纬度范围
        }
        //推送分页Map参数
        HashMap<String, Object> param = new HashMap();
        param.put("currentPage", (currentPage-1)*pageSize);
        param.put("pageSize", pageSize);
        param.put("merchantId", merchant.getId());
        int totalCount = cancelOrderRepository.selectCancelCountOrderByPage(param);
        List<CancelOrder> list = cancelOrderRepository.selectCancelOrderByPage(param);
        //创建返回对象
        CancelOrderCallBack  b = new CancelOrderCallBack();
        //推送订单列表
        b.setList(list);
        //计算总页数
        int totalPage = totalCount/pageSize;
        if(totalCount%pageSize!= 0)
            totalPage++;
        b.setTotalPage(totalPage);
        return new ResponseEntity<CancelOrderCallBack>(b, HttpStatus.OK);
    }
    @GetMapping("/vo/{id}")
    public ResponseEntity<OrderVO> getVObyId(@PathVariable Integer id, HttpServletRequest request) {
        OrderVO orderExt = cancelOrderExtRepository.selectVOById(id);
        return new ResponseEntity<OrderVO>(orderExt, HttpStatus.OK);
    }
}
